<template>
	<div>
		<Modal
			title="系统图库"
			:value="value"
			:width="width"
			:mask-closable="!uploading"
			@on-visible-change="handleChangeModal"
		>
			<div class="material-library">
				<div class="material-library-filter ui-flex">
					<div class="ui-flex-full">
						<RadioGroup v-model="params.mimetype" type="button" @on-change="handleChangeType">
					        <Radio label="image">图片</Radio>
					        <Radio label="video">视频</Radio>
					    </RadioGroup>
					</div>
					<div class="ui-form-inline">
						<Form :model="filterForm" inline @submit.native.prevent>
			                <FormItem label="分类">
			                	<Select v-model="filterForm.module" style="width: 120px">
			                		<Option value="">全部</Option>
			                		<Option v-for="(item, index) in categories" :key="index" :value="item.value">{{ item.title }}</Option>
							    </Select>
			                </FormItem>
			                <FormItem label="排序规则">
			                	<Select style="width: 120px">
							        <Option :value="0">按日期</Option>
							        <Option :value="1">按大小</Option>
							    </Select>
			                </FormItem>
			                <FormItem label="关键词">
			                    <Input v-model="filterForm.keywords" placeholder="请输入关键词搜索" suffix="ios-search" clearable style="width: 180px"></Input>
			                </FormItem>
			                <Button type="primary" @click="handleSearch">筛选</Button>
				    	</Form>
					</div>
				</div>
				<div class="material-library-body">
					<div class="material-library-content">
						<div class="material-library-content-cell" v-for="item in datas" :class="{checked: item.checked}" @click="handleCheckedData(item)">
							<div class="image-box">
								<ImageCell :width="198" :src="item.url"></ImageCell>
								<div class="mask"><Icon type="md-checkmark" /></div>
							</div>
							<div class="title">
								<p class="ui-ellipsis">图片名称：{{ item.name }}</p>
								<P>上传时间：{{ item.create_time }}</P>
							</div>
						</div>
					</div>
					<div class="material-library-page">
						<Page
							:total="totalNumber"
							:current="params.page"
							:page-size="params.limit"
							show-elevator
							@on-change="handleChangePage"
						/>
					</div>
				</div>
			</div>
			<div class="ui-flex ui-flex-between" slot="footer" style="text-align: left;">
				<div class="ui-flex-full">
					<div class="ui-flex">
						<Button type="primary" @click="handleShowUploadModal">上传图片/视频</Button>
						<div class="ui-flex-full" v-if="max > 0">
							<span style="margin-left: 20px; line-height: 32px; vertical-align: top;">已选择 {{ checkDatas.length }} / {{ max }} 项</span>
						</div>
					</div>
				</div>
				<div>
					<Button type="text" @click="handleChangeModal(false)">取消</Button>
					<Button type="primary" @click="handleSubmit">确定</Button>
				</div>
			</div>
		</Modal>
		<Modal
			v-model="showUploadModal"
			title="文件上传"
			:width="320"
			:closable="false"
			:mask-closable="false"
			footer-hide
		>
			<Form label-position="top">
				<FormItem label="选择分类">
					<Select v-model="uploadModule">
						<Option v-for="item in categories" :key="item.value" :value="item.value">{{ item.title }}</Option>
					</Select>
				</FormItem>
				<div class="ui-flex">
					<Upload
						:action="uploadPath"
						:data="{'module': uploadModule}"
						:show-upload-list="false"
						:format="['jpg','jpeg','png']"
						:before-upload="handleUploadBefore"
						:on-success="handleUploadSuccess"
						:on-error="handleUploadError"
					>
				        <Button type="success" :loading="uploading">{{ uploading ? '正在上传' : '上传图片'}}</Button>
				    </Upload>
					<div class="ui-flex-full" style="padding-left: 20px;">
						<Button @click="showUploadModal = false">关闭</Button>
					</div>
				</div>
			</Form>
		</Modal>
	</div>
</template>

<script>
import Util from '@/libs/util.js';
import ImageCell from '@/components/ImageCell/index.vue';
export default {
	name: 'materialLibrary',
	components: {
		ImageCell
	},
	props: {
		value: {
			type: Boolean,
			default: true
		},
		width: {
			type: String | Number,
			default: 880
		},
		module: {
			type: String,
			default: ''
		},
		// 最大可选数量，0时表示无限制
		max: {
			type: Number,
			default: 0
		}
	},
	data() {
		return {
			showUploadModal: false,
			uploading: false,
			uploadPath: Util.baseURL + '/api/v1/attachment/attachment/upload',
			uploadModule: '',
			categories: [
				{
            		title: '商品模块',
            		value: 'goods'
            	},
            	{
            		title: '用户模块',
            		value: 'user'
            	},
            	{
            		title: '店铺装修',
            		value: 'store'
            	},
            	{
            		title: '应用模块',
            		value: 'application'
            	},
            	{
            		title: '活动促销',
            		value: 'promotion'
            	}
			],
			filterForm: {
				module: ''
			},
			params: {
				module: '',
				mimetype: 'image',
				page: 1,
				limit: 8
			},
			totalNumber: 0,
			datas: [],
			checkDatas: []
		}
	},
	mounted() {
		this.init();
	},
	methods: {
		init() {
			Util.ajax.post(this.API['API_ATTACHMENT_LISTS'], this.params).then(res => {
				this.datas = res.data;
				this.params.page = res.current_page;
				this.totalNumber = res.total;
			}).catch(() => {
				
			})
		},
		// 切换类型
		handleChangeType() {
			this.params.page = 1;
			this.init();
		},
		// 选择分类
		handleSelectCategory(node, data) {
			this.params.module = data.value;
			this.handleChangePage(1);
		},
		// 搜索
		handleSearch() {
			this.params.module = this.filterForm.module;
			this.params.page = 1;
			this.init();
		},
		// 切换分页
		handleChangePage(page) {
			this.params.page = page;
			this.init();
		},
		// 显示上传弹窗
		handleShowUploadModal() {
			this.showUploadModal = true;
			this.uploadModule = this.params.module;
		},
		// 上传前
		handleUploadBefore() {
			if(this.uploadModule) {
				this.uploading = true;
				return true;
			}
			this.$Message.error('请选择图片所属模块');
			return false;
		},
		// 上传成功
		handleUploadSuccess(response, file, fileList) {
			this.uploading = false;
			if(response.code != 200) {
				this.$Message.error(response.message || '上传出错');
				return false;
			}
			if(this.params.module != this.uploadModule) {
				this.params.module = this.uploadModule;
				this.params.page = 1;
				this.init();
			}else{
				if(this.datas.length == 0) {
					this.datas.push(response.result);
				}else{
					this.datas.unshift(response.result);
					if(this.datas.length > 10) {
						this.datas.splice(10, 1);
					}
				}
			}
			this.showUploadModal = false;
		},
		// 上传失败
		handleUploadError() {
			this.uploading = false;
		},
		// 选择素材
		handleCheckedData(item) {
			if(item.checked == undefined) {
				this.$set(item,  'checked', true);
			}else{
				item.checked = !item.checked;
			}
			this.checkDatas = this.datas.filter(item => {
				return item.checked;
			})
		},
		handleSubmit() {
			/*let ids = this.checkDatas.map(item => {
				return item.id
			});*/
			if(this.max > 0 && this.checkDatas.length > this.max) {
				this.$Message.error('最多可以选择 '+ this.max +'张');
				return false;
			}
			this.$emit('change', this.checkDatas);
			this.handleChangeModal(false);
		},
		handleChangeModal(status) {
			if(!status) {
				this.checkDatas = [];
				this.datas = this.datas.map(item => {
					if(item.checked) {
						item.checked = false;
					}
					return item;
				})
			}
			this.$emit('input', status);
		}
	}
}
</script>

<style lang="less">
.material-library {
	height: 467px;
	&-filter {
		padding: 15px 20px 5px;
		border-bottom: 1px solid #ebebeb;
		background-color: #fafafa;
	}
	&-content {
		height: 340px;
		font-size: 0;
		overflow: hidden;
		overflow-y: auto;
		&-cell {
			display: inline-block;
			margin: 20px 0 0 20px;
			width: 200px;
			border: 1px solid #e1e2e3;
			.image-box {
				position: relative;
				width: 198px;
				height: 198px;
				.mask {
					display: none;
					position: absolute;
					top: 0;
					right: 0;
					bottom: 0;
					left: 0;
					color: #fff;
					font-size: 30px;
					line-height: 198px;
					text-align: center;
					background-color: rgba(0, 0, 0, .6);
					z-index: 2;
				}
			}
			.ui-image-cell {
				border: 0;
			}
			.title {
				padding: 5px;
				line-height: 23px;
				font-size: 12px;
				border-top: 1px solid #e1e2e3;
				cursor: pointer;
			}
		}
		&-cell.checked {
			border-color: #1c9df9;
			.image-box {
				.mask {
					display: block;
				}
			}
			.title {
				border-top-color: #1c9df9;
			}
		}
	}
	&-page {
		padding: 15px;
		height: 63px;
		text-align: right;
		border-top: 1px solid #e9ecee;
		background-color: #fff;
	}
}
.ivu-modal-body .material-library {
	margin: -16px;
}
</style>